package com.beaut.project.filter;

/**
 * 拦截JSP的过滤器
 */
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.beaut.project.interceptor.PermissionInterceptor;
import com.beaut.project.util.ServletUtility;


public class RequestJspFilter implements Filter{

	// 编码
	protected String encoding = null;
	@Override
	public void destroy() {
		this.encoding = null;
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String url = ((HttpServletRequest) request).getRequestURI();
		url = url.substring(url.indexOf(((HttpServletRequest) request).getContextPath())+((HttpServletRequest) request).getContextPath().length());
		PermissionInterceptor permissionInterceptor = new PermissionInterceptor();
		boolean isValidPriv = false;
		try {
			if (url.contains(".jsp")){
				isValidPriv = permissionInterceptor.preHandle((HttpServletRequest) request,(HttpServletResponse) response,new Object());
				if (!isValidPriv) {
					ServletUtility.forward("/core/inc/priverror.jsp",
							(HttpServletRequest) request,
							(HttpServletResponse) response);
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);
		chain.doFilter(request, response);
	}
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		this.encoding = arg0.getInitParameter("encoding");
	}

}
